package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {

    @Reference
    private RecommendUserService recommendUserService;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private QuestionService questionService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private VisitorService visitorService;

    @Reference
    private UserLocationService userLocationService;

    // 今日佳人
    public ResponseEntity findTodayBest() {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询今日佳人
        RecommendUser recommendUser = recommendUserService.findMaxScoreRecommendUser(userId);
        // 3.封装vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfoService.findByUserId(recommendUser.getUserId())); // userInfo
        vo.setFateValue(recommendUser.getScore().longValue()); // 缘分值
        // 4.返回vo
        return ResponseEntity.ok(vo);
    }

    // 推荐用户列表
    public ResponseEntity findRecommendUserVoByPage(Integer pageNum, Integer pageSize) {
        // 1.获取登录用户userId
        Long userId = UserHolder.get().getId();
        // 2 .调用rpc查询
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserByPage(userId, pageNum, pageSize);
        // 3.获取recommendUser集合
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        // 4.封装vo
        List<RecommendUserVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recommendUserList)) {
            for (RecommendUser recommendUser : recommendUserList) {
                // 创建vo
                RecommendUserVo vo = new RecommendUserVo();
                vo.setUserInfo(userInfoService.findByUserId(recommendUser.getUserId())); // userInfo
                vo.setFateValue(recommendUser.getScore().longValue()); // 缘分值

                // 添加到集合中
                voList.add(vo);
            }
        }
        // 5.将vo重置到分页对象
        pageBeanVo.setItems(voList);
        // 6.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    // 推荐用户详情
    public ResponseEntity findRecommendUserVoDetail(Long recommendUserId) {
        // 1.调用rpc查询推荐用户
        RecommendUser recommendUser = recommendUserService.findRecommendUserById(recommendUserId, UserHolder.get().getId());

        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(UserHolder.get().getId());
            recommendUser.setScore(0.0001D);
        }
        // 2.封装vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfoService.findByUserId(recommendUser.getUserId()));// 推荐用户信息
        vo.setFateValue(recommendUser.getScore().longValue());// 缘分值
        // 3.返回vo
        return ResponseEntity.ok(vo);
    }

    // 查看陌生人问题
    public ResponseEntity findStrangerQuestions(Long userId) {
        // 1.调用rpc查询
        Question question = questionService.findByUserId(userId);
        // 2.默认值处理
        if (question == null) {
            question = new Question();
            question.setStrangerQuestion("国民老公也是小舔狗吗???");
        }
        // 3.返回陌生人问题了
        return ResponseEntity.ok(question.getStrangerQuestion());
    }

    // 最近访客
    public ResponseEntity findVisitors() {
        // 0.声明voList
        List<VisitorVo> voList = new ArrayList<>();
        // 1.获取登录userId
        Long userId = UserHolder.get().getId();
        // 2.获取上次访问时间
        String lastAccessTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        // 3.如果有上次登录时间调用rpc查询历史访客
        if (StrUtil.isNotEmpty(lastAccessTime)) {
            List<Visitor> visitorList = visitorService.findLastAccessVisitorListByCondition(userId, Long.valueOf(lastAccessTime));
            // 4.封装vo
            if (CollectionUtil.isNotEmpty(visitorList)) {
                for (Visitor visitor : visitorList) {
                    // 创建vo
                    VisitorVo vo = new VisitorVo();
                    vo.setUserInfo(userInfoService.findByUserId(visitor.getVisitorUserId())); // 访客id
                    vo.setFateValue(visitor.getScore().longValue());// 访客缘分值

                    // 添加到集合中
                    voList.add(vo);
                }
            }
        }
        // 5. 记录本次登录时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");

        // 6.返回voList
        return ResponseEntity.ok(voList);
    }

    // 上传地理位置
    public void uploadLocation(double longitude, double latitude, String addrStr) {
        // 1.获取登录用户userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc保存坐标
        userLocationService.uploadUserLocation(userId, longitude, latitude, addrStr);
    }

    // 搜附近
    public ResponseEntity searchNearUserVo(String gender, Integer distance) {
        // 1.获取登录userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询附近的人
        List<Long> nearUserIdList = userLocationService.searchNearUser(userId, distance);

        // 3.封装Vo
        List<NearUserVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(nearUserIdList)) {
            for (Long nearUserId : nearUserIdList) {
                // 排除自己
                if (userId == nearUserId) {
                    continue;
                }
                // 排除异性
                UserInfo userInfo = userInfoService.findByUserId(nearUserId); // 附近人的信息
                if (!StrUtil.equals(gender, userInfo.getGender())) {
                    continue;
                }

                // 组装vo
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userInfo.getId());
                vo.setNickname(userInfo.getNickname());
                vo.setAvatar(userInfo.getAvatar());

                // 添加到集合中
                voList.add(vo);
            }
        }

        // 4.返回voList
        return ResponseEntity.ok(voList);

    }

    // 探花卡片
    public ResponseEntity tanhuaCards() {
        // 1.获取登录用户userId
        Long userId = UserHolder.get().getId();
        // 2 .调用rpc查询
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserByPage(userId, 1, 20);
        // 3.获取recommendUser集合
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        // 4.封装vo
        List<RecommendUserVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recommendUserList)) {
            for (RecommendUser recommendUser : recommendUserList) {
                // 创建vo
                RecommendUserVo vo = new RecommendUserVo();
                vo.setUserInfo(userInfoService.findByUserId(recommendUser.getUserId())); // userInfo
                vo.setFateValue(recommendUser.getScore().longValue()); // 缘分值

                // 添加到集合中
                voList.add(vo);
            }
        }
        // 5.返回voList
        return ResponseEntity.ok(voList);
    }
}
